<?php
class MainPage extends CI_Controller{
    public function __construct() {
        parent::__construct();
        $this->load->model('OceanBlog/Ob_login');
        $this->load->model('OceanBlog/Ob_blog');
        $this->load->helper('url_helper');
    }
    
    public function index(){
        $data['blog'] = $this->Ob_blog->getDefaultBlog('admin');
        $data['recentBlogList'] = $this->Ob_blog->getRecentBlogList('admin');
        $this->loadView('mainPage', $data);
    }
    
    public function view(){
        $id = $this->input->get('id');
        $data['blog'] = $this->Ob_blog->getBlog($id);
        $data['recentBlogList'] = $this->Ob_blog->getRecentBlogList('admin');
        $this->loadView('mainPage', $data);
    }
    
    public function writeBlog(){
        $data['recentBlogList'] = $this->Ob_blog->getRecentBlogList('admin');
        $this->loadView('write', $data);
    }
    
    public function insertBlog(){
        $content = $this->input->post('content');
        $title = $this->input->post('title');
        $username = $this->input->cookie('username');
//        $username = 'admin';
        $data = array();
        $result = $this->Ob_blog->insertBlog($username,$title,$content);
        
        if($result){
            $this->output->set_status_header(200)
                    ->set_content_type('application/json')
                    ->set_output(json_encode(array('msg' => 'Insert sucess' )));
        }else{
            $this->output->set_status_header(500)
                    ->set_content_type('application/json')
                    ->set_output(json_encode(array('msg' => 'Database error' )));
        }
        
    }
    
    public function blogList(){
        $data['recentBlogList'] = $this->Ob_blog->getRecentBlogList('admin');
        $data['blogList'] = $this->Ob_blog->getBlogList('admin');
        $this->loadView('blogList', $data);
    }
    
    public function loadView($viewName, $data){
        $this->load->view('OceanBlog/header');
        $this->load->view('OceanBlog/' . $viewName, $data);
        $this->load->view('OceanBlog/footer');
    }
}
